﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using EasyXaf.EntityDesigner.BusinessObjects;

namespace EasyXaf.EntityDesigner.Controllers;

public class RearrangeOrderViewController : ObjectViewController<ListView, ISortable>
{
    public SimpleAction RearrangeOrder { get; }

    public RearrangeOrderViewController()
    {
        RearrangeOrder = new SimpleAction(this, "RearrangeOrder", PredefinedCategory.View)
        {
            Caption = "重排顺序",
            ImageName = "RowIndex",
        };
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        RearrangeOrder.Execute += ResetOrder_Execute;
    }

    protected override void OnDeactivated()
    {
        RearrangeOrder.Execute -= ResetOrder_Execute;

        base.OnDeactivated();
    }

    private void ResetOrder_Execute(object sender, SimpleActionExecuteEventArgs e)
    {
        int order = 0;
        var objs = View.CollectionSource.List
            .OfType<ISortable>()
            .OrderBy(x => x.Order)
            .ToList();

        foreach (var obj in objs)
        {
            obj.Order = ++order;
        }
    }
}
